package com.store.app.activity;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.R;
import com.store.app.bean.BitmapBean;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.SettingData;
import com.store.app.utils.UtilsBitmap;
import com.yalantis.ucrop.CropUtils;
import com.yalantis.ucrop.UCrop;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Ben
 * on 2016/9/1 0001.\
 * 绑定银行卡页面
 */
public class BindBalanceActivity extends BaseActivity implements View.OnClickListener, IOnHttpListener {
    private TextView tvShowText;//显示上传照片
    private ImageView ivAddPhoto;//点击上传图片
    private ImageView ivOne, ivTwo, ivThree, ivFour, ivFive;
    private int currentPhoto = 0;//当前上传的图片数量
    private TextView tvTitle;   //标题

    private List<Bitmap> bitmapList = new ArrayList<>();
    private List<String> dosList = new ArrayList<String>();
    private EditText etNumber;//qq或者手机
    private EditText et_content;//银行账户
    private EditText et_acount;//用户名称

    private final int MSG_UPLOAD_PIC_SUCCESS = 1;//上传图片成功
    private final int MSG_SUBMIT_SUCCESS = 2;//提交用户反馈成功
    private final int MSG_SUBMIT_FAIL = 3;//提交用户反馈成功
    private final int MSG_NET_FAIL = 4;//网络不通
    private final int LOAD_PIC_FAIL = 5;//上传图片失败
    private final int SHOW_PIC = 6;//显示图片

    private NetRequest netRequest;


    private Button btSubmit;//提交

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                //上传图片成功,调用提交用户反馈的接口
                case MSG_UPLOAD_PIC_SUCCESS:
                    String content = et_content.getText().toString().trim() + et_acount.getText().toString().trim() + et_bank.getText().toString().trim();
                    String number = etNumber.getText().toString().trim();
                    Log.v("zyl", "要提交的图片：" + getDocIds());
                    netRequest.requestFeedBack(1, getDocIds(), number, content);
//                    new FeedBackRequest().start();
                    break;
                case MSG_SUBMIT_SUCCESS:
                    dismissProgressDialog();
                    Toast.makeText(BindBalanceActivity.this, "提交成功！", Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                case MSG_SUBMIT_FAIL:
                    dismissProgressDialog();
                    Toast.makeText(BindBalanceActivity.this, "提交失败！", Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                case MSG_NET_FAIL:
                    dismissProgressDialog();
                    Toast.makeText(BindBalanceActivity.this, "网络不通！", Toast.LENGTH_SHORT).show();
                    break;
                //上传图片失败
                case LOAD_PIC_FAIL:
                    Toast.makeText(BindBalanceActivity.this, "上传图片失败！", Toast.LENGTH_SHORT).show();
                    break;
                case SHOW_PIC:
                    if (bean.getBitmap() == null) {
                        return;
                    }
                    if (tempIndex == 0) {
                        iv_add_photo_one.setImageBitmap(bean.getBitmap());
                    } else if (tempIndex == 1) {
                        iv_add_photo_two.setImageBitmap(bean.getBitmap());
                    }
                    break;
            }
        }
    };
    private TextView et_bank;
    private EditText et_acount_zhihang;
    private EditText et_tv_cardholder;
    private EditText et_card_no;
    private ImageView iv_add_photo_one;
    private ImageView iv_add_photo_two;
    private EditText et_remark;
    private Button bt_submit;
    private static String localTempImageFileName = "";
    private static final int FLAG_CHOOSE_IMG = 5;                   //选择照片
    private static final int FLAG_CHOOSE_PHONE = 6;                 //选择拍照
    private static final int FLAG_MODIFY_FINISH = 7;
    private int chooseIndex = 0;                                    //记录选择图片的位置
    private String docIdOne, docIdTwo;
    //图片地址
    private String img_add = "";
    private ImageView public_ll_return;
    private LinearLayout ll_choose_bank;
    private String bank_code, bank_name;
    private Bitmap temBitmap;
    private int tempIndex = 0;
    private Uri fromFile;
    private BitmapBean bean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.v("zyl", "onCreate BindBalanceActivity");
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_bind_bank);
        netRequest = new NetRequest(this);
        initView();
    }

    private void initView() {
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        tvTitle.setText("绑定银行卡");
        btSubmit = (Button) findViewById(R.id.bt_submit);
        btSubmit.setOnClickListener(this);
        iv_add_photo_one = (ImageView) findViewById(R.id.iv_add_photo_one);
        iv_add_photo_one.setOnClickListener(this);
        iv_add_photo_two = (ImageView) findViewById(R.id.iv_add_photo_two);
        iv_add_photo_two.setOnClickListener(this);
        et_bank = (TextView) findViewById(R.id.et_bank);
        et_bank.setOnClickListener(this);
        et_acount_zhihang = (EditText) findViewById(R.id.et_acount_zhihang);
        et_acount_zhihang.setOnClickListener(this);
        et_tv_cardholder = (EditText) findViewById(R.id.et_tv_cardholder);
        et_tv_cardholder.setOnClickListener(this);
        et_card_no = (EditText) findViewById(R.id.et_card_no);
        et_card_no.setOnClickListener(this);
        iv_add_photo_one = (ImageView) findViewById(R.id.iv_add_photo_one);
        iv_add_photo_one.setOnClickListener(this);
        iv_add_photo_two = (ImageView) findViewById(R.id.iv_add_photo_two);
        iv_add_photo_two.setOnClickListener(this);
        et_remark = (EditText) findViewById(R.id.et_remark);
        et_remark.setOnClickListener(this);
        bt_submit = (Button) findViewById(R.id.bt_submit);
        bt_submit.setOnClickListener(this);
        public_ll_return = (ImageView) findViewById(R.id.public_ll_return);
        public_ll_return.setOnClickListener(this);
        ll_choose_bank = (LinearLayout) findViewById(R.id.ll_choose_bank);
        ll_choose_bank.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //选择银行
            case R.id.ll_choose_bank:
                Log.v("zyl", "选择银行");
                Intent intent = new Intent(BindBalanceActivity.this, ChooseBankActivity.class);
                startActivityForResult(intent, 10);
                break;
            case R.id.iv_add_photo_one:
                chooseIndex = 0;
                getPic();
                break;
            case R.id.iv_add_photo_two:
                getPic();
                chooseIndex = 1;
                break;
            case R.id.public_ll_return:
                finish();
                break;
            case R.id.bt_submit:
                String bank = et_bank.getText().toString().trim();
                String zhihang = et_acount_zhihang.getText().toString().trim();
                String cardHolder = et_tv_cardholder.getText().toString().trim();
                String cardNo = et_card_no.getText().toString().trim();
                String remark = et_remark.getText().toString().trim();
                if (TextUtils.isEmpty(bank)) {
                    Toast.makeText(BindBalanceActivity.this, "请选择开户银行！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(zhihang)) {
                    Toast.makeText(BindBalanceActivity.this, "请输入开户支行！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(cardHolder)) {
                    Toast.makeText(BindBalanceActivity.this, "请输入持卡人姓名！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(cardNo)) {
                    Toast.makeText(BindBalanceActivity.this, "请输入银行卡号！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (cardNo.length() < 15) {
                    Toast.makeText(BindBalanceActivity.this, "请输入正确的银行卡号！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(docIdOne)) {
                    Toast.makeText(BindBalanceActivity.this, "请上传银行卡正反面！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(docIdTwo)) {
                    Toast.makeText(BindBalanceActivity.this, "请上传银行卡正反面！", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(bank_code)) {
                    Toast.makeText(BindBalanceActivity.this, "获取不到组织机构代码", Toast.LENGTH_SHORT).show();
                    return;
                }
                showProgressDialog("", "提交中", false);

                netRequest.requestBindCard(1, cardNo, cardHolder, bank_code, bank_name, remark, docIdOne, docIdTwo);
                break;
        }
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //拿到裁剪后的图片
        if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) {
            if (data != null) {
                final Uri resultUri = UCrop.getOutput(data);
                bean = UtilsBitmap.addFilePath3(resultUri.getPath(), this);
                Log.v("zyl", "判断图片上传的位置：" + chooseIndex);
                if (chooseIndex == 0) {
                    netRequest.requestUploadPic(3, bean.getIsBm());
                } else if (chooseIndex == 1) {
                    netRequest.requestUploadPic(4, bean.getIsBm());
                }
            }
        } else if (resultCode == UCrop.RESULT_ERROR) {
            Toast.makeText(BindBalanceActivity.this, "图片剪切失败！", Toast.LENGTH_SHORT)
                    .show();
        }

        //拿到从图库中选择的图片
        if (requestCode == FLAG_CHOOSE_IMG && resultCode == RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
                    CropUtils.startCropActivity(uri, BindBalanceActivity.this, 5, 3);
                }
            }
        } else if (requestCode == FLAG_CHOOSE_PHONE && resultCode == RESULT_OK) {
            File f = new File(SettingData.FILE_PIC_SCREENSHOT, localTempImageFileName);
            Uri uri = Uri.fromFile(f);
            Log.d("lxp", "========" + uri);
            if (uri != null) {
                UtilsBitmap.getCompressUri(uri);
                CropUtils.startCropActivity(uri, BindBalanceActivity.this, 5, 3);     //进入裁剪页面
            }
            Log.v("zyl", "uri   ——:" + uri.toString());
        } else if (requestCode == 10 && resultCode == 88) {
            Log.v("zyl", "获取到数据");
            if (data != null) {
                bank_name = data.getStringExtra("bank_name");
                bank_code = data.getStringExtra("bank_code");
                Log.v("zyl", "name:" + bank_name);
                Log.v("zyl", "CODE:" + bank_code);
                et_bank.setText(bank_name);
            }
        }


    }

    @Override
    public void onAfinalFail() {
        dismissProgressDialog();
        Toast.makeText(BindBalanceActivity.this, "网络不通！", Toast.LENGTH_SHORT).show();
        finish();
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        Log.v("zyl", "请求成功:" + result);
        dismissProgressDialog();
        if (requestId == 1) {
            Toast.makeText(BindBalanceActivity.this, "提交成功，请耐心等待工作人员审核！", Toast.LENGTH_SHORT).show();
            finish();
        } else if (requestId == 3) {
            //图片上传成功
            String doc_id = null;
            try {
                JSONObject obj = new JSONObject(result);
                doc_id = obj.getString("doc_id");
                docIdOne = doc_id;
                if (bean == null) {
                    return;
                }
                iv_add_photo_one.setImageBitmap(bean.getBitmap());
            } catch (Exception e) {
            }
        } else if (requestId == 4) {
            String doc_id = null;
            try {
                JSONObject obj = new JSONObject(result);
                doc_id = obj.getString("doc_id");
                docIdTwo = doc_id;
                if (bean == null) {
                    return;
                }
                iv_add_photo_two.setImageBitmap(bean.getBitmap());
            } catch (Exception e) {
            }
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        Log.v("zyl", "请求失败:" + msg);
        dismissProgressDialog();
        Toast.makeText(BindBalanceActivity.this, msg, Toast.LENGTH_SHORT).show();
    }


    public String getDocIds() {
        String docIds = "";
        for (int i = 0; i < dosList.size(); i++) {
            docIds += dosList.get(i) + ",";
        }
        if (!TextUtils.isEmpty(docIds)) {
            docIds = docIds.substring(0, docIds.length() - 1);
        }
        return docIds;
    }


    public void getPic() {
        new AlertDialog.Builder(BindBalanceActivity.this)
                .setTitle("请选择图片来源")
                .setItems(new String[]{"相册", "相机"},
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                if (which == 0) {
                                    Intent intent = new Intent(
                                            Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                    startActivityForResult(intent,
                                            FLAG_CHOOSE_IMG);
                                } else if (which == 1) {
                                    String status = Environment
                                            .getExternalStorageState();
                                    if (status.equals(Environment.MEDIA_MOUNTED)) {
                                        try {
                                            localTempImageFileName = "";
                                            localTempImageFileName = String
                                                    .valueOf((new Date())
                                                            .getTime())
                                                    + ".png";
                                            File filePath = SettingData.FILE_PIC_SCREENSHOT;
                                            if (!filePath.exists()) {
                                                filePath.mkdirs();
                                            }
                                            Intent intent = new Intent(
                                                    MediaStore.ACTION_IMAGE_CAPTURE);
                                            File f = new File(filePath,
                                                    localTempImageFileName);
                                            // localTempImgDir和localTempImageFileName是自己定义的名字
                                            fromFile = Uri.fromFile(f);
                                            intent.putExtra(
                                                    MediaStore.Images.Media.ORIENTATION,
                                                    0);
                                            intent.putExtra(
                                                    MediaStore.EXTRA_OUTPUT,
                                                    fromFile);
                                            startActivityForResult(
                                                    intent,
                                                    FLAG_CHOOSE_PHONE);
                                        } catch (ActivityNotFoundException e) {
                                            //
                                        }
                                    }
                                }

                            }
                        }).show();
    }
}
